package com.lvy.hczn.transmit.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lvy.hczn.front.common.constant.Constants;
import com.lvy.hczn.front.common.core.domain.AjaxResult;
import com.lvy.hczn.front.common.core.domain.entity.SysDictData;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.common.utils.DictUtils;
import com.lvy.hczn.front.framework.jwt.utils.JwtUtils;
import com.lvy.hczn.front.system.domain.business.GoodsBoxDetail;
import com.lvy.hczn.front.system.domain.business.Sku;
import com.lvy.hczn.front.system.domain.business.Spu;
import com.lvy.hczn.mq.rocket.ProducerUtil;
import com.lvy.hczn.front.common.constant.MqConstants;
import com.lvy.hczn.mq.rocket.ParamInfo;
import com.lvy.hczn.transmit.domain.ProductSupplierGoodsBarcode;
import com.lvy.hczn.transmit.domain.TemperAreaConfig;
import com.lvy.hczn.transmit.domain.dto.cteck.ProductSellerGoods;
import com.lvy.hczn.transmit.service.TSpuService;
import com.lvy.hczn.transmit.service.TemperAreaConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class TSpuServiceImpl implements TSpuService {

    @Autowired
    private ProducerUtil producerUtil;

    @Autowired
    private TemperAreaConfigService temperAreaConfigService;

    @Override
    @Deprecated
    public AjaxResult syncSpuBatch(HttpServletRequest request, ParamInfo<ProductSellerGoods> info) throws Exception {
        if (info.getList() == null || info.getList().isEmpty()) {
            throw new UtilException("数据为空");
        }
        String username = "";
        String tokenHeader = request.getHeader(JwtUtils.AUTH_TOKEN);
        if (!StrUtil.isEmpty(tokenHeader)) {
            username = JwtUtils.getUserName(tokenHeader);
        }
//        producerUtil.sendMsg(MqConstants.TOPIC_SYNC_SPU, info.getWarehouseCode(), JSONUtil.toJsonStr(info).getBytes(StandardCharsets.UTF_8), IdUtil.fastUUID());
        return AjaxResult.success();
    }


    /**
     * 数据转换
     *
     * @param info
     * @return void
     * @author yw
     * @date 2023-05-06 10:07:44
     */
    @Override
    public void convertData(ParamInfo<ProductSellerGoods> info, String username) throws Exception {
        ParamInfo<Spu> categoryParamInfo = new ParamInfo<>();
        if (info.getList() != null && !info.getList().isEmpty()) {
            categoryParamInfo.setList(new ArrayList<>());
            List<ProductSellerGoods> list = JSON.parseArray(JSONUtil.toJsonStr(info.getList()), ProductSellerGoods.class);
            for (int i = 0; i < list.size(); i++) {
                ProductSellerGoods goods = list.get(i);
                Spu spu = new Spu();
                initData(spu, goods, username);
                categoryParamInfo.getList().add(spu);
            }
        } else {
            ProductSellerGoods productSellerGoods = JSON.parseObject(JSONUtil.toJsonStr(info.getData()), ProductSellerGoods.class);
            if (info.getData() != null && productSellerGoods.getProductId() != null) {
                Spu spu = new Spu();
                initData(spu, productSellerGoods, username);
                categoryParamInfo.setData(spu);
            } else {
                throw new UtilException("数据为空");
            }
        }
        categoryParamInfo.setWarehouseCode(info.getWarehouseCode());
        producerUtil.sendMsg(MqConstants.TOPIC_SYNC_SPU, null, JSON.toJSONString(categoryParamInfo).getBytes(StandardCharsets.UTF_8), IdUtil.fastUUID());
    }

    /**
     * 数据转换
     *
     * @param spu
     * @param goods
     * @author yw
     * @date 2023-05-05 10:27:38
     */
    @Override
    public Spu initData(Spu spu, ProductSellerGoods goods, String username) {
        spu.setSourceId(goods.getProductId() + Constants.SOURCE_ID_DEFAULT + goods.getProductSysCode());
        spu.setSpuCode(goods.getProductSysCode());
        spu.setCategoryId(goods.getCategoryId());
        spu.setId(goods.getProductId());
        spu.setName(goods.getProductName());
        spu.setSupplierCode(goods.getSupplierCode());
        //两个都不存在时，赋值为0，其中一个存在在赋值给另一个
        if (goods.getErrorMax() == null) {
            if (goods.getErrorMin() != null) {
                goods.setErrorMax(goods.getErrorMin());
            } else {
                if (goods.getList() != null && !goods.getList().isEmpty()) {
                    BigDecimal sum = goods.getList().stream().map(ProductSupplierGoodsBarcode::getFloatRange).reduce(BigDecimal.ZERO, BigDecimal::add);
                    goods.setErrorMax(sum);
                } else {
                    goods.setErrorMax(BigDecimal.ZERO);
                }
            }
        }
        if (goods.getErrorMin() == null) {
            goods.setErrorMin(goods.getErrorMax());
        }
        spu.setStandard(goods.getStandard());
        spu.setBigProduct(goods.getBigProduct());
        spu.setErrorMin(goods.getErrorMin());
        spu.setErrorMax(goods.getErrorMax());
        TemperAreaConfig temperAreaConfig = temperAreaConfigService.getOne(Wrappers.<TemperAreaConfig>lambdaQuery().eq(TemperAreaConfig::getId, goods.getStorageTemperatureRange()));
        if (temperAreaConfig != null) {
            spu.setTemperatureZoneCode(temperAreaConfig.getTemperatureZoneCode());
        } else {
            spu.setTemperatureZoneCode(Integer.valueOf(goods.getStorageTemperatureRange()));
        }
        String prefix = "";
        List<SysDictData> sysDictDataList = DictUtils.getDictCache(Constants.PLATFORM_DOMAIN);
        if (sysDictDataList != null) {
            for (SysDictData dictData : sysDictDataList) {
                if (dictData.getDictLabel().equals(Constants.PLATFORM_DOMAIN_IMG)) {
                    prefix = dictData.getDictValue();
                    break;
                }
            }
        }
        spu.setImgUrl(prefix + goods.getProductUrl());
        if (goods.getList() != null) {
            spu.setList(JSON.parseArray(JSON.toJSONString(goods.getList()), Sku.class));
        }
        //有效期模式 1固定有效日期、2自购买之日起
        /*if (goods.getExpireDateType() == 1) {
            Date expireDate = DateUtils.addDays(DateUtils.toDate(goods.getOutputDate()), goods.getExpireDate());
            LocalDateTime localDateTime = LocalDateTimeUtil.of(expireDate);
            spu.setShelfLife(localDateTime.toLocalDate());
        }
        spu.setTemperatureZoneCode(goods.getTemperatureZoneCode());
        if (goods.getGoodsBarcode() != null && !goods.getGoodsBarcode().isEmpty()) {
            List<Sku> skuList = new ArrayList<>();
            for (ProductSupplierGoodsBarcode barcode : goods.getGoodsBarcode()) {
                Sku sku = new Sku();
                sku.setId(String.valueOf(barcode.getBarcodeId()));
                sku.setSpuCode(barcode.getProductSysCode());
                sku.setSkuCode(barcode.getBarcodeSysCode());
            }
        }*/
        return spu;
    }
}
